package com.huyn.baseframework.net;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.RequestQueue.RequestFilter;
import com.android.volley.Response;
import com.android.volley.toolbox.FileRequest;
import com.android.volley.toolbox.Volley;

/**
 * @author huyn
 * @version 2013-12-9 下午4:43:26
 */

public class PluginPkgLoader {

	private static PluginPkgLoader mInstance = null;
	private RequestQueue mRequestQueue;
	private Context mContext;

	private PluginPkgLoader(Context context) {
		mContext = context;
		mRequestQueue = Volley.newRequestQueue(context, 5);
	}

	public static PluginPkgLoader getInstance(Context context){
		if(mInstance == null){
			mInstance = new PluginPkgLoader(context.getApplicationContext());
		}
		return mInstance;
	}

	public void stop() {
		try {
			if(mRequestQueue != null)
				mRequestQueue.stop();
		} catch(Exception e) {

		}
	}

	public void start() {
		try {
			if(mRequestQueue != null)
				mRequestQueue.start();
		} catch (Exception e) {

		}
	}

	public void cancelRequest(Object tag) {
		if(mRequestQueue != null)
			mRequestQueue.cancelAll(tag);
	}

	public void cancelAllRequest() {
		if(mRequestQueue != null)
			mRequestQueue.cancelAll(new RequestFilter() {

				@Override
				public boolean apply(Request<?> request) {
					return true;
				}
			});
	}

	public void startPluginLoader(String url, String fileName, boolean canUseSDCard, Response.Listener<String> mRequestListener, Response.ProgressListener mProgressListener) {
		FileRequest request = new FileRequest(url, mRequestListener, mProgressListener);

		String pkgName = mContext.getPackageName().replace(".", "_");
		request.setFileTitle(pkgName + "_" + fileName);
		request.setCanUseSDCard(canUseSDCard);
		mRequestQueue.add(request);
	}

	public void release() {
		this.mRequestQueue = null;
		mInstance = null;
	}

}
